from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UploadImageSerializer
from shortuuid import uuid
import os
from django.conf import settings

class UploadImage(APIView):
    def post(self, request):
        #1.验证图片格式是否正确
        serializer = UploadImageSerializer(data=request.data)
        if serializer.is_valid():
            file = serializer.validated_data.get('image')
            #更换文件名
            file_name = uuid() + os.path.splitext(file.name)[-1]
            path = settings.MEDIA_ROOT / file_name
            try:
                with open(path, 'wb') as fp:
                    for chunk in file.chunks():
                        fp.write(chunk)
            except Exception as e:
                return Response({'errno': 1, "message":"图片保存失败"})
            file_url = settings.MEDIA_URL + file_name
            return Response({"errno":0, "data":{"url":file_url, "alt":"", "href":file_url}})
        else:
            print(serializer.errors)
            return Response({"errno":1,"message":list(serializer.errors.values())[0][0]})
